<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'type', 'amount', 'order_no',
        'out_trade_no', 'status', 'trader_message', 'paid_at', 'remark'
    ];

    public static function generateSerialNumber()
    {
        $rand = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 12);
        $randomString = date('Ymd') . $rand;

        if (self::query()->where('order_no', $randomString)->exists()) {
            return self::generateSerialNumber();
        }

        return $randomString;
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
